<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

/**
 * 快递查询类
 */
class ExpressQuery {
    private $db;
    private $token;
    private $apiUrl;
    private $sfPhoneTail;
    
    public function __construct() {
        $this->db = getDB();
        $this->loadConfig();
    }
    
    private function loadConfig() {
        $stmt = $this->db->query("SELECT key_name, key_value FROM settings");
        $settings = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $settings[$row['key_name']] = $row['key_value'];
        }
        
        $this->token = $settings['express_token'] ?? '';
        $this->apiUrl = $settings['express_api_url'] ?? 'https://music.wxnotes.cn/kd';
        $this->sfPhoneTail = $settings['sf_phone_tail'] ?? '';
    }
    
    /**
     * 检查账户余额
     */
    public function checkBalance() {
        if (empty($this->token)) {
            throw new Exception('请先配置快递查询Token');
        }
        
        $url = rtrim($this->apiUrl, '/') . '/balance.php';
        
        $data = [
            'token' => $this->token
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'User-Agent: OrderSystem/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        // 记录调试信息
        error_log("余额查询响应 - HTTP代码: $httpCode, 错误: $error, 响应: " . substr($response, 0, 200));
        
        if ($httpCode !== 200) {
            // 如果是502错误，可能是服务暂时不可用，返回一个友好的错误信息
            if ($httpCode == 502) {
                throw new Exception('快递查询服务暂时不可用，请稍后重试 (502 Bad Gateway)');
            }
            throw new Exception('余额查询接口请求失败，HTTP代码: ' . $httpCode . '，错误: ' . $error);
        }
        
        if (empty($response)) {
            throw new Exception('接口返回空响应');
        }
        
        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('接口返回数据格式错误: ' . json_last_error_msg() . '，响应: ' . $response);
        }
        
        // 检查余额查询返回的数据结构
        if (isset($result['error'])) {
            throw new Exception($result['error']);
        }
        
        if (isset($result['balance'])) {
            // 直接返回余额
            return floatval($result['balance']);
        } elseif (isset($result['data']) && isset($result['data']['balance'])) {
            // 嵌套在data中的余额
            return floatval($result['data']['balance']);
        } else {
            throw new Exception('无法解析余额信息，返回数据: ' . json_encode($result));
        }
    }
    
    /**
     * 测试接口连接性
     */
    public function testConnection() {
        if (empty($this->token)) {
            throw new Exception('请先配置快递查询Token');
        }
        
        $url = rtrim($this->apiUrl, '/') . '/balance.php';
        
        $data = [
            'token' => $this->token
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'User-Agent: OrderSystem/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        return [
            'http_code' => $httpCode,
            'error' => $error,
            'response' => $response
        ];
    }
    
    /**
     * 查询快递信息
     */
    public function queryTracking($trackingNo) {
        if (empty($this->token)) {
            throw new Exception('请先配置快递查询Token');
        }
        
        if (empty($trackingNo)) {
            throw new Exception('物流单号不能为空');
        }
        
        $url = rtrim($this->apiUrl, '/') . '/query.php';
        
        // 处理顺丰快递单号格式
        $finalTrackingNo = $this->formatTrackingNumber($trackingNo);
        
        $data = [
            'token' => $this->token,
            'orderNumber' => $finalTrackingNo
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'User-Agent: OrderSystem/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception('快递查询接口请求失败，HTTP代码: ' . $httpCode . '，错误: ' . $error);
        }
        
        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('接口返回数据格式错误: ' . json_last_error_msg());
        }
        
        if (isset($result['error'])) {
            throw new Exception($result['error']);
        }
        
        // 检查返回的数据结构
        if (isset($result['data']) && is_string($result['data'])) {
            // data字段是字符串，需要再次解析
            $dataResult = json_decode($result['data'], true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $result['data'] = $dataResult;
            }
        }
        
        // 检查物流查询状态
        if (isset($result['data']['status']) && $result['data']['status'] !== '0') {
            $errorMsg = $this->getErrorMessage($result['data']['status']);
            throw new Exception($errorMsg);
        } elseif (isset($result['status']) && $result['status'] !== '0') {
            $errorMsg = $this->getErrorMessage($result['status']);
            throw new Exception($errorMsg);
        }
        
        return $result;
    }
    
    /**
     * 格式化物流单号（处理顺丰快递）
     */
    private function formatTrackingNumber($trackingNo) {
        // 检查是否为顺丰快递（不区分大小写）
        if (stripos($trackingNo, 'SF') === 0 && !empty($this->sfPhoneTail)) {
            // 已经是正确格式的跳过
            if (strpos($trackingNo, ':') === false) {
                return $trackingNo . ':' . $this->sfPhoneTail;
            }
        }
        return $trackingNo;
    }
    
    /**
     * 获取错误信息
     */
    private function getErrorMessage($status) {
        $errors = [
            '201' => '快递单号错误',
            '203' => '快递公司不存在',
            '204' => '快递公司识别失败',
            '205' => '没有物流信息',
            '207' => '该单号被限制，错误单号'
        ];
        
        return $errors[$status] ?? '未知错误 (状态码: ' . $status . ')';
    }
    
    /**
     * 保存物流信息到数据库
     */
    public function saveTrackingInfo($orderId, $trackingNo, $expressData) {
        // 解析物流数据
        $result = $this->parseExpressData($expressData);
        
        if (!$result) {
            throw new Exception('无法解析物流数据');
        }
        
        // 检查是否已存在记录
        $stmt = $this->db->prepare("SELECT id FROM order_tracking WHERE order_id = ?");
        $stmt->execute([$orderId]);
        $exists = $stmt->fetch();
        
        if ($exists) {
            // 更新记录
            $stmt = $this->db->prepare("UPDATE order_tracking SET 
                express_data = ?, status = ?, deliverystatus = ?, issign = ?, 
                expName = ?, updateTime = ?, query_count = query_count + 1, 
                last_query_at = NOW(), updated_at = NOW()
                WHERE order_id = ?");
            $stmt->execute([
                json_encode($expressData, JSON_UNESCAPED_UNICODE),
                $expressData['status'] ?? '',
                $result['deliverystatus'] ?? '',
                $result['issign'] == '1' ? 1 : 0,
                $result['expName'] ?? '',
                $result['updateTime'] ?? '',
                $orderId
            ]);
        } else {
            // 新增记录
            $stmt = $this->db->prepare("INSERT INTO order_tracking 
                (order_id, tracking_no, express_data, status, deliverystatus, issign, expName, updateTime, query_count, last_query_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())");
            $stmt->execute([
                $orderId,
                $trackingNo,
                json_encode($expressData, JSON_UNESCAPED_UNICODE),
                $expressData['status'] ?? '',
                $result['deliverystatus'] ?? '',
                $result['issign'] == '1' ? 1 : 0,
                $result['expName'] ?? '',
                $result['updateTime'] ?? ''
            ]);
        }
        
        // 如果已签收，更新订单签收状态
        if (isset($result['issign']) && $result['issign'] == '1') {
            $stmt = $this->db->prepare("UPDATE orders SET is_signed = 1 WHERE id = ? AND is_signed = 0");
            $stmt->execute([$orderId]);
        }
        
        return true;
    }
    
    /**
     * 解析物流数据
     */
    private function parseExpressData($expressData) {
        if (isset($expressData['result'])) {
            return $expressData['result'];
        } elseif (isset($expressData['data']['result'])) {
            return $expressData['data']['result'];
        } elseif (isset($expressData['data']) && is_array($expressData['data'])) {
            return $expressData['data'];
        }
        return null;
    }
    
    /**
     * 获取物流详情
     */
    public function getTrackingDetails($orderId) {
        $stmt = $this->db->prepare("SELECT * FROM order_tracking WHERE order_id = ?");
        $stmt->execute([$orderId]);
        $tracking = $stmt->fetch();
        
        if (!$tracking) {
            return null;
        }
        
        $expressData = json_decode($tracking['express_data'], true);
        $result = $this->parseExpressData($expressData);
        
        return [
            'tracking_info' => $tracking,
            'express_data' => $expressData,
            'parsed_result' => $result
        ];
    }
}

// API 路由处理
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    $expressQuery = new ExpressQuery();
    
    switch ($action) {
        case 'query':
            $trackingNo = $_POST['tracking_no'] ?? '';
            $orderId = intval($_POST['order_id'] ?? 0);
            
            if (empty($trackingNo)) {
                throw new Exception('物流单号不能为空');
            }
            
            $result = $expressQuery->queryTracking($trackingNo);
            $expressQuery->saveTrackingInfo($orderId, $trackingNo, $result);
            
            echo json_encode([
                'success' => true,
                'data' => $result,
                'message' => '物流查询成功'
            ]);
            break;
            
        case 'get_details':
            $orderId = intval($_GET['order_id'] ?? 0);
            $details = $expressQuery->getTrackingDetails($orderId);
            
            if ($details && $details['tracking_info']) {
                echo json_encode([
                    'success' => true,
                    'data' => $details
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => '暂无物流信息'
                ]);
            }
            break;
            
        case 'check_balance':
            $balance = $expressQuery->checkBalance();
            
            // 更新余额到设置
            $db = getDB();
            $stmt = $db->prepare("INSERT INTO settings (key_name, key_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE key_value = ?");
            $stmt->execute(['express_balance', $balance, $balance]);
            $stmt->execute(['express_balance_updated', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')]);
            
            echo json_encode([
                'success' => true,
                'balance' => $balance,
                'message' => '余额查询成功'
            ]);
            break;
            
        case 'test_connection':
            $connectionInfo = $expressQuery->testConnection();
            echo json_encode([
                'success' => $connectionInfo['http_code'] == 200,
                'data' => $connectionInfo,
                'message' => $connectionInfo['http_code'] == 200 ? '连接正常' : '连接失败'
            ]);
            break;
            
        case 'batch_update':
            $orderIds = json_decode($_POST['order_ids'] ?? '[]', true);
            $results = [];
            $db = getDB();
            
            foreach ($orderIds as $orderId) {
                $stmt = $db->prepare("SELECT id, tracking_no FROM orders WHERE id = ?");
                $stmt->execute([$orderId]);
                $order = $stmt->fetch();
                
                if ($order && !empty($order['tracking_no'])) {
                    try {
                        $result = $expressQuery->queryTracking($order['tracking_no']);
                        $expressQuery->saveTrackingInfo($orderId, $order['tracking_no'], $result);
                        
                        $results[] = [
                            'order_id' => $orderId,
                            'success' => true,
                            'message' => '更新成功'
                        ];
                    } catch (Exception $e) {
                        $results[] = [
                            'order_id' => $orderId,
                            'success' => false,
                            'message' => $e->getMessage()
                        ];
                    }
                } else {
                    $results[] = [
                        'order_id' => $orderId,
                        'success' => false,
                        'message' => '订单不存在或没有物流单号'
                    ];
                }
            }
            
            echo json_encode([
                'success' => true,
                'results' => $results,
                'message' => '批量更新完成'
            ]);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => '未知操作'
            ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>